# File Name:mqtt_chat_client.py
# Python Version:3.5.1

import paho.mqtt.client as mqtt
import json
import time

HOST = "184.170.220.88"
PORT = 1883

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    client.subscribe("/World")
    client.publish("/World", json.dumps({"user": "user", "say": "Hello,anyone!"}))


def on_message(client, userdata, msg):
    print(msg.topic+" :"+str(msg.payload))
    #print(msg.topic+":"+str(msg.payload.decode()))
    #print(msg.topic+":"+msg.payload.decode())
##    payload = json.loads(msg.payload.decode())
##    print(payload.get("user")+":"+payload.get("say"))


def client_loop():
    client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    client = mqtt.Client(client_id)
    client.username_pw_set("admin", "123456")
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    print("connecy success")
    client.loop_forever()
    
if __name__ == '__main__':
    client_loop()
